import { InfiniteScroll, Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import http from '../../api'
import Loading from '../../components/publicComponents/Loading'
import PubNav from '../../components/publicComponents/pubNav'
import { CategoryResultType } from '../../myTypes'
import style from './idex.module.css'

export default function Category() {
  const location = useLocation()
  const navigate = useNavigate()
  let [userId, setUserId] = useState('')
  const [title, setTile] = useState('')
  let [category, setCategory] = useState(1)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [dataList, setDateList] = useState<
    Array<{
      id: number
      name: string
      img: string
      price: number
      storeId: number
    }>
  >([])

  useEffect(() => {
    if (location.state) {
      const categoryId = location.state.category as number
      switch (categoryId) {
        case 1:
          setTile('乡村民宿')
          break
        case 2:
          setTile('生态美食')
          break
        case 3:
          setTile('户外玩乐')
          break
        case 4:
          setTile('特产商城')
          break
      }
    }
    const id = localStorage.getItem('userId')
    if (id) {
      userId = id
      setUserId(id)
    } else {
      navigate('/login')
    }
  }, [])

  function formatDate(): Array<string> {
    let date = new Date()
    const date2 = new Date(date.getTime() + 24 * 3600 * 1000)
    let today = date.toLocaleDateString().split('/')
    let tomorrow = date2.toLocaleDateString().split('/')
    today[1] = parseInt(today[1]) < 10 ? '0' + today[1] : today[1]
    tomorrow[1] = parseInt(tomorrow[1]) < 10 ? '0' + tomorrow[1] : tomorrow[1]

    today[2] = parseInt(today[2]) < 10 ? '0' + today[2] : today[2]
    tomorrow[2] = parseInt(tomorrow[2]) < 10 ? '0' + tomorrow[2] : tomorrow[2]
    return [today.join('-'), tomorrow.join('-')]
  }

  async function getDataList() {
    let categoryId: number
    if (page === 1) {
      categoryId = location.state.category as number
      category = categoryId
      setCategory(categoryId)
    }

    let data = {}
    let url = ''
    if (category === 1) {
      console.log(111)
      url = '/mty/pension/search'
      data = {
        pageNum: page,
        pageSize: 10,
        accountId: userId,
        orderBy: 'complex',
        key: '',
        num: '',
        checkInTime: formatDate()[0],
        leaveTime: formatDate()[1]
      }
    } else {
      url = '/mty/category/getByCategoryId'
      data = {
        num: page,
        size: 10,
        accountId: userId,
        orderBy: 'complex',
        key: '',
        categoryId: category
      }
    }
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const result = await http('get', url, data)
    Toast.clear()
    if (result) {
      const data = result.data as CategoryResultType
      const newData = data.list.map((item) => ({
        id: item.id,
        name: item.name,
        img: item.img,
        price: item.price,
        storeId: item.storeId
      }))
      setDateList((preDate) => [...preDate, ...newData])
      setPage((prePage) => prePage + 1)
      setHasMore(newData.length > 0)
      console.log(newData)
    }
  }

  function goDetail(id: number, storeId: number) {
    if (category !== 1) {
      navigate(`/detail?id=${id}`, {
        state: {
          storeId,
          id
        }
      })
    }
  }

  return (
    <div style={{ paddingTop: '46px' }}>
      <PubNav title={title} />
      <div className={style['category-lis']}>
        {dataList.map((item) => (
          <div
            className={style['category-item']}
            key={item.id}
            onClick={() => {
              goDetail(item.id, item.storeId)
            }}
          >
            <div className={style['category-pic']}>
              <img src={item.img} alt="" />
            </div>
            <div className={style['category-title']}>{item.name}</div>
            <div className={style['category-price']}>
              <div className={style['price']}>
                <span>￥</span>
                <span className={style['price-num']}>{item.price}</span>
                <span className={style['text']}>起</span>
              </div>
              <div className={style['icon']}>
                <img src="/static/use/icon-btn-more-9e9.png" alt="" />
              </div>
            </div>
          </div>
        ))}
      </div>
      <InfiniteScroll threshold={10} loadMore={getDataList} hasMore={hasMore}>
        {!hasMore && <span>----我也是有底线的----</span>}
      </InfiniteScroll>
    </div>
  )
}
